<template>
  <el-container class="voucher-management">
    <!-- 操作按钮 -->
    <el-header>
      <el-button type="primary" @click="onNew">新增</el-button>
      <el-button type="danger" @click="onDelete">删除</el-button>
      <el-button type="success" @click="onAudit">审核</el-button>
      <el-button type="warning" @click="onReverseAudit">反审核</el-button>
      <el-button @click="onExport">导出</el-button>
      <el-button @click="onImport">导入</el-button>
      <el-button @click="onOrganize">整理</el-button>
    </el-header>

    <!-- 表格 -->
    <el-main>
      <el-table
        :data="vouchers"
        border
        row-key="voucherId"
        :default-expand-all="true"
        style="width: 100%"
      >
        <!-- 日期列 -->
        <el-table-column prop="voucherDate" label="日期" width="100" />
        <!-- 凭证编号 -->
        <el-table-column label="凭证编号" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.wordName + "-" + row.voucherNo }}</el-tag>
          </template>
        </el-table-column>

        <!-- 附件 -->
        <el-table-column prop="attachmentCount" label="附件" width="80">
          <template #default="{ row }">
            <span v-if="row.attachmentCount != 0">
              {{ row.attachmentCount }}
            </span>
            <el-button
              v-if="row.attachmentCount == 0"
              type="text"
              size="small"
              @click="onAddAttachment(row)"
            >
              添加附件
            </el-button>
          </template>
        </el-table-column>
        <!-- 制单人 -->
        <el-table-column prop="createBy" label="制单人" width="100" />

        <!-- 状态 -->
        <el-table-column prop="auditStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.auditStatus == 0" type="success">未审核</el-tag>
            <el-tag v-if="row.auditStatus == 1" type="danger">已审核</el-tag>
            <el-tag v-if="row.auditStatus == 2" type="warning">反审核</el-tag>
            <el-tag v-if="row.auditStatus == 3" type="info">已红冲</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reversalTime" label="红冲时间" width="130">
          <template #default="{ row }">
            <span v-if="row.reversalTime != null">
              {{ row.reversalTime }}
            </span>
            <span v-if="row.reversalTime == null">未冲红</span>
          </template>
        </el-table-column>
        <!-- 录入时间 -->
        <el-table-column prop="createTime" label="录入时间" width="180" />
        <!-- 审核人 -->
        <el-table-column prop="auditor" label="审核人" width="100" />
        <!-- 审核时间 -->
        <el-table-column prop="auditTime" label="审核时间" width="180">
          <template #default="{ row }">
            <span v-if="row.auditTime != null"> {{ row.auditTime }} </span>
            <span v-if="row.auditTime == null">未审核</span>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="onAudit(row)"
              >审核</el-button
            >
            <el-button type="text" size="small" @click="onReverseAudit(row)"
              >反审核</el-button
            >
            <el-button type="text" size="small" @click="onRedo(row)"
              >冲红</el-button
            >
            <el-button type="text" size="small" @click="onInsert(row)"
              >插入</el-button
            >
            <el-button type="text" size="small" @click="onPrint(row)"
              >打印</el-button
            >
            <el-button type="text" size="small" @click="onCopy(row)"
              >复制</el-button
            >
            <el-button type="text" size="small" @click="onEdit(row)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="onDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>

        <!-- 展开行 -->
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table :data="row.voucherDetailList" border style="width: 100%">
              <el-table-column prop="summaryContent" label="摘要" />
              <el-table-column prop="subjectName" label="科目名称" />
              <el-table-column
                prop="debitAmount"
                label="借方金额"
                width="250"
              />
              <el-table-column
                prop="creditAmount"
                label="贷方金额"
                width="250"
              />
            </el-table>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
  </el-container>

  <div>
    <el-dialog
      v-model="dialogTableVisible"
      title="Shipping address"
      width="1300"
    >
      <h2 style="text-align: center">记账凭证</h2>
      <hr
        style="width: 400px; height: 1px; border: 0; background-color: #000"
      />
      <hr
        style="width: 400px; height: 2px; border: 0; background-color: #000"
      />

      <div>
        <!-- 表单 -->
        <el-form :model="voucherForm" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="3">
              <el-form-item label="凭证字">
                <el-select
                  v-model="voucherForm.wordId"
                  placeholder="请选择凭证字"
                  @change="onWordChange()"
                  style="width: 60px"
                >
                  <el-option
                    v-for="item in voucehrWordList"
                    :key="item.wordId"
                    :label="item.wordName"
                    :value="item.wordId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="凭证号">
                <el-input
                  v-model="voucherForm.voucherNumber"
                  placeholder="请输入凭证号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="凭证日期">
                <el-date-picker
                  v-model="voucherForm.date"
                  type="date"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="附单据">
                <el-input-number
                  v-model="voucherForm.attachmentCount"
                  :min="0"
                  placeholder="请输入附单据数量"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-button type="primary" @click="uploadAttachment">
                上传附件
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div>
        <!-- 表格 -->
        <el-table
          :data="voucherForm.voucherDetails"
          border
          style="width: 100%"
          :default-expand-all="false"
        >
          <el-table-column prop="index" label="序号" width="50" />
          <el-table-column prop="summary" label="摘要">
            <template #default="{ row }">
              <input @click="openDialog()" v-model="row.summaryId" />
              <!-- 弹窗 -->
              <!-- <el-dialog
                v-model="dialogVisibleSummary"
                title="选择摘要"
                width="30%"
                @close="dialogVisibleSummary = false"
              >
                <div>
                  <el-input
                    aria-label="摘要名称"
                    v-model="queryParamSummary.summaryContent"
                    placeholder="请输入关键字"
                    style="width: 70%; margin-bottom: 20px"
                  />
                  <el-button
                    style="margin-bottom: 20px; margin-left: 50px"
                    @click="selectSummaryByQuery()"
                    >查询</el-button
                  >
                  <select
                    v-model="row.summary"
                    size="large"
                    aria-placeholder="请选择"
                    style="width: 70%"
                  >
                    <option
                      v-for="item in summaryList"
                      :key="item.id"
                      :label="item.summaryContent"
                      :value="item.summaryId"
                    />
                  </select>
                  <el-button style="margin-left: 50px" @click="addHtml()"
                    >确定</el-button
                  >
                </div>
              </el-dialog> -->
              <el-dialog
                v-model="dialogVisibleSummary"
                title="Shipping address"
                width="500"
              >
                <div>
                  <el-input
                    aria-label="摘要名称"
                    v-model="queryParamSummary.summaryContent"
                    placeholder="请输入关键字"
                    style="width: 70%; margin-bottom: 20px"
                  />
                  <el-button
                    style="margin-bottom: 20px; margin-left: 50px"
                    @click="selectSummaryByQuery()"
                    >查询</el-button
                  >
                  <select
                    v-model="row.summary"
                    size="large"
                    aria-placeholder="请选择"
                    style="width: 70%"
                  >
                    <option
                      v-for="item in summaryList"
                      :key="item.id"
                      :label="item.summaryContent"
                      :value="item.summaryId"
                    />
                  </select>
                  
                </div>
                <template #footer>
                  <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false"
                      >Cancel</el-button
                    >
                    <el-button
                      type="primary"
                      @click="dialogFormVisible = false"
                    >
                      Confirm
                    </el-button>
                  </div>
                </template>
              </el-dialog>
            </template>
          </el-table-column>
          <el-table-column prop="accountingSubject" label="会计科目" />
          <el-table-column prop="debitAmount" label="借方金额">
            <template #default="{ row }">
              <el-input-number
                v-model="row.debitAmount"
                :min="0"
                placeholder="请输入借方金额"
              />
            </template>
          </el-table-column>
          <el-table-column prop="creditAmount" label="贷方金额">
            <template #default="{ row }">
              <el-input-number
                v-model="row.creditAmount"
                :min="0"
                placeholder="请输入贷方金额"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{ row, $index }">
              <el-button type="text" size="small" @click="deleteRow($index)">
                删除行
              </el-button>
              <el-button type="text" size="small" @click="addRow">
                添加行
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="moveRow($index, 'up')"
                :disabled="$index === 0"
              >
                上移
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="moveRow($index, 'down')"
                :disabled="$index === voucherDetails.length - 1"
              >
                下移
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 合计 -->
        <div class="total">
          合计：
          <span>借方金额：{{ totalDebitAmount }}</span>
          <span>贷方金额：{{ totalCreditAmount }}</span>
        </div>
      </div>
    </el-dialog>
  </div>

  <div></div>
</template>

<script>
import { ref } from "vue";
import "element-plus/dist/index.css";
import { listVoucher_manage } from "@/api/voucher/voucher_manage";
import { selectVoucherWord } from "@/api/voucher/voucher_word";
import { getSummaryAll } from "@/api/voucher/summary";
import { da } from "element-plus/es/locales.mjs";
import { ElButton, ElDrawer } from "element-plus";
// 在 main.js 或 main.ts 中
import "element-plus/dist/index.css";

const vouchers = ref();

const getList = () => {
  listVoucher_manage().then((response) => {
    vouchers.value = response.data;
  });
};

export default {
  name: "VoucherManagement",
  setup() {
    // 操作方法
    // 使用 ref 创建响应式变量
    const dialogTableVisible = ref(false);

    // 表单数据
    const voucherForm = ref({
      wordId: "",
      voucherNumber: "",
      date: "",
      attachmentCount: 0,
      voucherDetails: [
        {
          index: 1,
          summaryId: "",
          accountingSubject: "",
          debitAmount: 111,
          creditAmount: 0,
        },
      ],
    });

    const voucherDetails = ref(voucherForm.value.voucherDetails);
    // 添加行
    const addRow = () => {
      const newRow = {
        index: voucherForm.value.voucherDetails.length + 1,
        summary: "",
        accountingSubject: "",
        debitAmount: 0,
        creditAmount: 0,
      };
      voucherForm.value.voucherDetails.push(newRow);
    };

    // 删除行
    const deleteRow = (index) => {
      voucherDetails.value.splice(index, 1);
      updateIndices();
    };

    // 移动行
    const moveRow = (currentIndex, direction) => {
      const targetIndex =
        direction === "up" ? currentIndex - 1 : currentIndex + 1;
      const [movedRow] = voucherForm.value.voucherDetails.splice(
        currentIndex,
        1
      );
      voucherForm.value.voucherDetails.splice(targetIndex, 0, movedRow);
      updateIndices();
    };

    // 合计计算
    const totalDebitAmount = computed(() =>
      voucherDetails.value.reduce(
        (sum, row) => sum + parseFloat(row.debitAmount),
        0
      )
    );

    const totalCreditAmount = computed(() =>
      voucherDetails.value.reduce(
        (sum, row) => sum + parseFloat(row.creditAmount),
        0
      )
    );

    // 上传附件
    const uploadAttachment = () => {
      ElMessage.success("附件上传成功！");
    };

    //凭证字下拉框集合
    const voucehrWordList = ref([]);
    //摘要下拉框集合
    const summaryList = ref([]);

    // 获取摘要下拉框集合
    const getSummaryList = (aaa) => {
      getSummaryAll(aaa).then((response) => {
        summaryList.value = response.data;
      });
    };

    // 摘要信息弹窗事件
    const dialogVisibleSummary = ref(false);
    const queryParamSummary = ref({
      summaryContent: "",
    });

    const selectSummaryByQuery = () => {
      summaryList.value = [];
      getSummaryList(queryParamSummary.value);
    };

    // 打开弹窗事件
    const openDialog = (row) => {
      dialogVisibleSummary.value = true;
      getSummaryList(null);
    };
    // 新增弹窗事件
    const onNew = () => {
      // 如果列表表格数据为空时，添加一行
      if (voucherForm.value.voucherDetails.length === 0) {
        voucherForm.value.voucherDetails.push({
          index: voucherForm.value.voucherDetails.length + 1,
          summary: "",
          accountingSubject: "",
          debitAmount: 0,
          creditAmount: 0,
        });
      }

      selectVoucherWord().then((response) => {
        voucehrWordList.value = response.data;
        voucherForm.value.wordId = response.data[0].wordId;
      });

      dialogTableVisible.value = true; // 打开弹窗
      console.log("新增111");
    };
    const onDelete = (row) => {
      console.log("删除", row);
    };
    const onAudit = (row) => {
      console.log("审核", row);
    };
    const onReverseAudit = (row) => {
      console.log("反审核", row);
    };
    const onExport = () => {
      console.log("导出");
    };
    const onImport = () => {
      console.log("导入");
    };
    const onOrganize = () => {
      console.log("整理");
    };
    const onAddAttachment = (row) => {
      console.log("添加附件", row);
    };
    const onRedo = (row) => {
      console.log("冲红", row);
    };
    const onInsert = (row) => {
      console.log("插入", row);
    };
    const onPrint = (row) => {
      console.log("打印", row);
    };
    const onCopy = (row) => {
      console.log("复制", row);
    };
    const onEdit = (row) => {
      console.log("编辑", row);
    };

    return {
      voucherDetails,
      voucherForm,
      vouchers,
      dialogTableVisible,
      totalDebitAmount,
      totalCreditAmount,
      voucehrWordList,
      dialogVisibleSummary,
      queryParamSummary,
      selectSummaryByQuery,
      summaryList,
      openDialog,
      moveRow,
      uploadAttachment,
      addRow,
      deleteRow,
      onNew,
      onDelete,
      onAudit,
      onReverseAudit,
      onExport,
      onImport,
      onOrganize,
      onAddAttachment,
      onRedo,
      onInsert,
      onPrint,
      onCopy,
      onEdit,
    };
  },
};

getList();
</script>
<style scoped>
.el-drawer {
  display: block !important;
  visibility: visible !important;
}
</style>

<style>
.voucher-management {
  padding: 20px;
}
.el-drawer {
  z-index: 9999 !important; /* 保证最大层级 */
}
</style>
